<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\WxClient;
use App\Services\Repo\CompanyRepo;
use App\Services\Repo\WxClientRepo;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Helper;

use App\Http\Requests;

/**
 * Class CompanyWxclientController
 * @package App\Http\Controllers
 */
class CompanyWxclientController extends Controller
{
    protected $_comService;
    protected $_wxclientService;
    /**@var Company $_company **/
    protected $_company;
    public function __construct(CompanyRepo $_comRepo, WxClientRepo $_wxclientRepo)
    {
        $this->_comService = $_comRepo;
        $this->_wxclientService = $_wxclientRepo;
        $id = request()->route()->getParameter('company', 0);
        $this->_company = Company::find($id);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (is_null($this->_company)) {
            $total = 0;
            $data = [];
        } else {
            $data = $this->_company->wxClients->map(function($wxClient) {
                return $this->_wxclientService
                    ->wxClientInfo($wxClient, $wxClient::WXClIENT_SET_FIELDS);
            });
            $total = $data->count();
        }
        return compact('total', 'data');
    }

    /**
     * 分配给尚未创建的渠道一批微信号
     *
     * @return mixed
     */
    public function create()
    {
        if (is_null($this->_company)) {
            return $this->_error('该渠道不存在');
        }
        $opts = Helper::get_filter();
        $wxClientCount = array_get($opts, 'wxClientCount', 0);
        if ($wxClientCount > 0) {
            // 获取空闲微信号
            /** @var Collection $data **/
            $data = $this->_wxclientService->getFreeClients($wxClientCount)
                ->map(function($wxClient) {
                    return $this->_wxclientService
                        ->wxClientInfo($wxClient, $wxClient::WXClIENT_SET_FIELDS);
                });
            // 检查数量
            $total = $data->count();
            if ($total < intval($wxClientCount) ){
                return $this->_error('空闲微信号数量不足');
            }
            $this->_wxclientService->freeze($data->pluck('_id')->all());
            return compact('total', 'data');
        }
        return $this->_error('需要分配的微信号数量必须大于0');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if (is_null($this->_company)) {
            return $this->_error('该渠道不存在');
        }
        // 分配微信号, 获取缓存的ID
        $wx_ids = $request->input('wx_ids', []);
        $origin_wx_ids = $this->_company->wxClients()
            ->select('_id')
            ->get()
            ->pluck('_id')
            ->all();
        $del_wx_ids = array_values(array_diff($origin_wx_ids, $wx_ids));
        $add_wx_ids = array_values(array_diff($wx_ids, $origin_wx_ids));

        if ($del_wx_ids) {
            (new WxClientRepo)
                ->unsetClientsFromCompany($this->_company->id, $del_wx_ids);
        }
        if ($add_wx_ids) {
            $realAddIds = (new WxClientRepo)
                ->setClientsToCompany($this->_company->id, $wx_ids);
        }

        // 微信数更新
        $update = ['wxClientCount'
            => WxClient::where('company_id', $this->_company->_id)->count()];
        $this->_company->update($update);

        $this->_wxclientService->unfreeze();
        // 解除锁定
        if ($add_wx_ids) {
            // 未添加成功微信号。
            $error_wx_ids = array_diff($add_wx_ids, $realAddIds);
            return array_values($error_wx_ids);
        }
        return [];
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($company_id, $wxClientId)
    {
        if ($wxClientId !== 'create')
            return $this->_error('参数错误');
        if (is_null($this->_company))
            return $this->_error('渠道不存在');
        $this->_wxclientService->unfreeze();
        return [];
    }
}
